package cn.z2huo.knowledge.concurrency.producerconsumer;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *
 * @author z2huo
 */
class CommunicatePetStore {

    private static final DataBuffer<Data> buffer = new DataBuffer<>();

    static Callable<Data> produce = () -> {
        Data data = Datas.produceOne();

        try {
            buffer.add(data);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return data;
    };

    static Callable<Data> consume = () -> {
        Data data = null;
        try {
            data = buffer.fetch();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    };

    /**
     * <p>线程数量
     */
    private static final int THREAD_TOTAL = 20;

    private static final int PRODUCE_COUNT = 5;

    private static final int CONSUME_COUNT = 10;

    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_TOTAL);

        for (int i = 0; i < PRODUCE_COUNT; i++) {
            threadPool.submit(new Producer(produce, 100));
        }

        for (int i = 0; i < CONSUME_COUNT; i++) {
            threadPool.submit(new Consumer(consume, 100));
        }

        threadPool.close();
    }

}
